﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Reflection;
using DataObject;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

/// <summary>
/// Summary description for FileManager
/// </summary>
public class FileManager
{
    public Type classType;
    public List<Object> objects;
    private const char DELIMITED_RECORD = '$';
    public FieldInfo[] fieldsInfos;
    public List<string> fieldNames;
    private IDataObject dbObj;

    public FileManager(Type classType)
    {
        objects = new List<object>();
        this.classType = classType;
        classType.GetMembers();
        fieldsInfos = classType.GetFields();
        fieldNames = new List<string>(Array.ConvertAll<FieldInfo, string>(fieldsInfos, new Converter<FieldInfo, string>(getFieldName)));
    }

    private string getFieldName(FieldInfo fieldInfo)
    {
        return fieldInfo.Name;
    }

    #region Public methods

    public Object[] ReadStream(StreamReader sr)
    {
        while (sr.Peek() >= 0)
        {
            string strline = sr.ReadLine();
            string[] records = strline.Split(DELIMITED_RECORD);
            Object obj = Activator.CreateInstance(classType);
            if (records != null && !records[0].Equals(""))
            {
                for (int i = 0; i < fieldsInfos.Length; i++)
                {
                    this.Populate(obj/*, setMethods[i]*/, records[i], fieldsInfos[i]);
                }
                objects.Add(obj);
            }
        }
        return objects.ToArray();
    }

    #endregion

    #region Private Methods    

    private void Populate(Object obj/*, MethodInfo method*/, string value, FieldInfo valueType)
    {
        Type t = valueType.FieldType;
        Object v = value.Trim();
        if (t.Equals(typeof(int)))
        {
            try
            {
                v = Convert.ToInt32(value);
            }
            catch (FormatException ex)
            {
                v = 0;
            }
        }
        valueType.SetValue(obj, v);
    }
    #endregion
}
